/*
 * *
 *  * Created with IntelliJ RustRover.
 *  * Description:
 *  * Copyright Author: ZhenYi
 *  * DateTime: 2024/2/14 下午5:10
 *
 */
use salvo::{Depot, handler, Request, Response};
use salvo::http::StatusCode;
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};
use serde::{Deserialize, Serialize};
use crate::config::pgsql::userlist;
use crate::utensil::basic_local::LocalBasicAuth;
use crate::utensil::cookie_local::LocalCookie;



/// 登录输入
/// username: 用户名
/// password: 密码
#[derive(Deserialize,Serialize)]
pub struct LoginInput{
    username:String,
    password:String
}


#[handler]
pub async fn login_admin<'a>(req: &mut Request,depot: &mut Depot, res: &mut Response){
    let input =match req.parse_json::<LoginInput>().await{
        Ok(i) => i,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Json parse error E0001\"}");
            return;
        }
    };
    let db = depot.obtain::<DatabaseConnection>().unwrap();
    return match userlist::Entity::find()
        .filter(userlist::Column::Username.contains(input.username.as_str()))
        .one(db)
        .await.unwrap() {
        None => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"User not found\"}");
        }
        Some(odk) => {
            if odk.password == input.password {
                if odk.genre == 1 {
                   res.status_code(StatusCode::ACCEPTED).render("{ \"OK\":\"OK\"}");
                    let ck_rc = depot.obtain::<LocalCookie>().unwrap().clone();
                    let cookie = ck_rc.generate_save_cookie(odk).await;
                    let auth = depot.obtain::<LocalBasicAuth>().unwrap();
                    let au = auth.generate_save_auth_basic_admin().await;
                    res.add_header("BasicAuth",format!("{}:{}",au.username(),au.password()),true).unwrap();
                    res.add_cookie(cookie);
                    return;
                } else {
                    res.status_code(StatusCode::IM_USED).render("{\"Error\":\"User not admin\"}");
                    return;
                }
            } else {
                res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Password error\"}");
                return;
            }
        }
    }
}
#[handler]
pub async fn login_author(req: &mut Request,depot: &mut Depot, res: &mut Response){
    let input =match req.parse_json::<LoginInput>().await{
        Ok(i) => i,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Json parse error\"}");
            return;
        }
    };
    let db = depot.obtain::<DatabaseConnection>().unwrap();
    let ck_rc = depot.obtain::<LocalCookie>().unwrap();
    return match userlist::Entity::find()
        .filter(userlist::Column::Username.contains(input.username.as_str()))
        .one(db)
        .await.unwrap() {
        None => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"User not found\"}");
        }
        Some(odk) => {
            if odk.password == input.password {
                if odk.genre == 2 {
                   res.status_code(StatusCode::ACCEPTED).render("{ \"OK\":\"OK\"}");
                    res.add_cookie(ck_rc.generate_save_cookie(odk).await);
                    let auth = depot.obtain::<LocalBasicAuth>().unwrap();
                    let au = auth.generate_save_auth_basic_author().await;
                    res.add_header("BasicAuth",format!("{}:{}",au.username(),au.password()),true).unwrap();
                    return;
                } else {
                    res.status_code(StatusCode::IM_USED).render("{\"Error\":\"User not admin\"}");
                    return;
                }
            } else {
                res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Password error\"}");
                return;
            }
        }
    }
}
#[handler]
pub async fn login_expert(req: &mut Request,depot: &mut Depot, res: &mut Response){
    let input =match req.parse_json::<LoginInput>().await{
        Ok(i) => i,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Json parse error\"}");
            return;
        }
    };
    let db = depot.obtain::<DatabaseConnection>().unwrap();
    let ck_rc = depot.obtain::<LocalCookie>().unwrap();
    return match userlist::Entity::find()
        .filter(userlist::Column::Username.contains(input.username.as_str()))
        .one(db)
        .await.unwrap() {
        None => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"User not found\"}");
        }
        Some(odk) => {
            if odk.password == input.password {
                if odk.genre == 3 {
                    res.status_code(StatusCode::ACCEPTED).render("{ \"OK\":\"OK\"}");
                    res.add_cookie(ck_rc.generate_save_cookie(odk).await);
                    let auth = depot.obtain::<LocalBasicAuth>().unwrap();
                    let au = auth.generate_save_auth_basic_expert().await;
                    res.add_header("BasicAuth",format!("{}:{}",au.username(),au.password()),true).unwrap();
                    return;
                } else {
                    res.status_code(StatusCode::IM_USED).render("{\"Error\":\"User not admin\"}");
                    return;
                }
            } else {
                res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Password error\"}");
                return;
            }
        }
    }
}
